import React, { useState } from 'react';
import { Modal, Upload, DatePicker, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { importSalaries } from '@/api/salary';
import dayjs from 'dayjs';

const { Dragger } = Upload;

interface ImportModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

interface ImportResult {
  success: boolean;
  message?: string;
  errors?: string[];
}

const ImportModal: React.FC<ImportModalProps> = ({
  open,
  onCancel,
  onSuccess,
}) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [salaryMonth, setSalaryMonth] = useState<dayjs.Dayjs | null>(null);
  const [loading, setLoading] = useState(false);

  const handleOk = async () => {
    if (!salaryMonth) {
      message.warning('请选择工资月份');
      return;
    }

    if (fileList.length === 0) {
      message.warning('请选择要导入的文件');
      return;
    }

    try {
      setLoading(true);
      const file = fileList[0].originFileObj as File;
      const month = salaryMonth.format('YYYY-MM');
      const errors = await importSalaries(file, month);
      
      if (errors && errors.length > 0) {
        message.warning(`导入完成，存在${errors.length}条错误`);
      } else {
        message.success('导入成功');
        onSuccess();
      }
    } catch (error) {
      // 错误已在request.ts中处理
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setFileList([]);
    setSalaryMonth(null);
    onCancel();
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    fileList,
    beforeUpload: (file) => {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        message.error('只能上传Excel文件！');
        return false;
      }
      return false;
    },
    onChange: ({ fileList }) => {
      setFileList(fileList);
    },
  };

  return (
    <Modal
      title="导入工资数据"
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
    >
      <div style={{ marginBottom: 16 }}>
        <DatePicker
          picker="month"
          value={salaryMonth}
          onChange={(date) => setSalaryMonth(date)}
          style={{ width: '100%' }}
        />
      </div>
      <Dragger {...uploadProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
        <p className="ant-upload-hint">
          支持 .xlsx 或 .xls 格式的Excel文件
        </p>
      </Dragger>
    </Modal>
  );
};

export default ImportModal; 